<template>
  <view class="setting-container">
    <!-- 顶部导航栏 -->
    <u-navbar
      :leftText="title"
      left-icon="arrow-left"
      left-icon-color="#303133"
      bg-color="#ffffff"
      fixed
      placeholder
      @left-click="back"
    />

    <!-- 主要内容区域 -->
    <view class="content-container">
      <!-- 绑定手机号 -->
      <view class="setting-item phone-item">
        <view class="setting-item__label">绑定手机号</view>
        <view class="setting-item__content">
          <text class="phone-number">{{ getMaskedNumber(phoneNumber) || '未绑定' }}</text>
		   <a href="javascript:void(0);" class="modify-link" style=" margin-left:0;" @click="openPhoneInputPopup">修改</a>
          <!-- <u-icon name="arrow-right" size="16" color="#909399"  @click="openPhoneInputPopup" /> -->
            <!-- <u-icon name="arrow-right" size="16" color="#909399" /> -->
        </view>
      </view>

      <!-- 余额支付密码 -->
      <view class="setting-item" >
        <view class="setting-item__label">余额支付密码</view>
        <view class="setting-item__content">
          <text class="password-status">········</text>
          <text class="protection-tag">保护中</text>
          <a href="javascript:void(0);" class="modify-link" @click="openSetPasswordPopup">修改/设置</a>
        </view>
      </view>
    </view>

    <!-- 手机号输入弹窗 -->
    <up-popup
      :show="showPhoneInputPopup"
      :closeable="true"
      @close="showPhoneInputPopup = false"
      mode="bottom"
      :round="16"
    >
      <view class="popup-container">
        <view class="popup-title">更换新手机号</view>
        <view class="popup-content">
          <u-form :model="phoneForm" :rules="phoneRules" label-position="top" label-width="auto" labelStyle="font-size: 36rpx;font-weight: bold;color: #303133;padding-bottom: 10px;" ref="phoneFormRef">
            <u-form-item prop="phone" class="form-item" label="新手机号"  >
				<u-input
				  v-model="phoneForm.phone"
				  placeholder="请输入手机号码"
				  type="number"
				  maxlength="11"
				  class="phone-input"
				/>
            
            </u-form-item>
            <u-form-item prop="phoneCode" class="form-item" borderBottom label="验证码"  label-position="top" label-width="auto">
              <u-input
                v-model="phoneForm.phoneCode"
                placeholder="请输入验证码"
                type="number"
                maxlength="6"
                class="verification-input"
              >
			  <template #suffix>
			  	<up-button @tap="sendVerificationCode" :text="sendBtnText" type="primary" plain size="normal" style="flex: 0.7;" :disabled="sendBtnDisabled" :loading="sendCodeLoading"></up-button>
			  </template>
			  </u-input>
             <!-- <up-button #right @tap="sendVerificationCode" :text="sendBtnText" type="primary" plain size="normal" style="flex: 0.5; margin-left: 10px;"
                :disabled="sendBtnDisabled" :loading="sendCodeLoading"></up-button> -->
            </u-form-item>
          </u-form>
        </view>
        <button class="confirm-button" @click="confirmPhoneInput">确定</button>
      </view>
    </up-popup>
    <phone-popup 
      v-model:show-bind-phone-popup="showBindPhonePopup"
      v-model:phone-number="phoneNumber"
    />
    
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import { onShow  } from '@dcloudio/uni-app'
import { getUpdateCode, checkCode, setNewPwd, updatePhone } from '@/api/auth'
import  phonePopup from '@/components/phone-popup.vue'
import * as Auth from "@/api/auth.js";
// 设置页面标题
const title = ref("账号与安全");

// 控制弹窗显示
const showBindPhonePopup = ref(false);
const showPhoneInputPopup = ref(false);

// 表单引用
const phoneFormRef = ref(null);

const phoneForm = reactive({
  phone: '',
  phoneCode: ''
});
// 显示的手机号
const phoneNumber = ref('151****0012');
const getMaskedNumber = (phone) => {
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};
const userInfo = ref({});
const flushInfo = () => {
  userInfo.value =  JSON.parse(uni.getStorageSync('userInfo'))
  console.log('userInfo', userInfo)
  phoneNumber.value = userInfo.value.info.phone
}

// 发送验证码按钮状态
const sendBtnDisabled = ref(false);
const sendBtnText = ref('发送验证码');
const sendCodeLoading = ref(false);
let countdownTimer = null;

// 验证规则
const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  phoneCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入有效的6位数字验证码', trigger: 'blur' }
  ]
};




// 返回上一页
const back = () => {
  uni.navigateBack({
    delta: 1
  });
};

// 打开手机号输入弹窗
const openPhoneInputPopup = () => {
  showPhoneInputPopup.value = true;

  // 重置表单
  if (phoneFormRef.value) {
    phoneFormRef.value.resetFields();
  }
  // 重置发送按钮状态
  sendBtnDisabled.value = false;
  sendBtnText.value = '发送验证码';
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
};


// 发送验证码
const sendVerificationCode = () => {
  // 先验证手机号
  phoneFormRef.value.validateField('phone')
    .then((v) => {
      if (!phoneForm.phone.trim()) {
      	return;
      }
      
      if (!/^1[3-9]\d{9}$/.test(phoneForm.phone)) {
      	return;
      }
      if(phoneForm.phone === phoneNumber.value){
		  uni.showToast({
		  	title: `当前手机号已经是${phoneForm.phone}!`,
			icon: "none"
		  });
		  return;
	  }
      // 手机号验证通过
      sendBtnDisabled.value = true;
      sendCodeLoading.value = true;
      sendBtnText.value = '发送中...';
      let countdown = 60;

     // 模拟发送验证码API调用
     Auth.getUpdateCode(phoneForm.phone).then(res => {
     	if (res.code == 200) {
			sendCodeLoading.value = false;
			sendBtnText.value = `${countdown}秒后重新发送`;
			
			countdownTimer = setInterval(() => {
			  countdown--;
			  if (countdown > 0) {
			    sendBtnText.value = `${countdown}秒后重新发送`;
			  } else {
			    clearInterval(countdownTimer);
			    countdownTimer = null;
			    sendBtnDisabled.value = false;
			    sendBtnText.value = '重新发送验证码';
			  }
			}, 1000);
     		uni.showToast({
     			title: '验证码发送成功',
     			icon: 'success'
     		});
     	} else {
			sendCodeLoading.value = false;
			sendBtnDisabled.value = false;
			sendBtnText.value = '发送验证码';
     		uni.showToast({
     			title: res.msg,
     			icon: 'none'
     		});
     	}
     }).catch(error=>{
		 sendCodeLoading.value = false;
		 sendBtnDisabled.value = false;
		 sendBtnText.value = '发送验证码';
		 console.log(error)
	 })
    })
    .catch(error => {
      // 手机号验证失败
      console.log('手机号验证失败：', error);
    });
};
// 确认手机号输入
const confirmPhoneInput = () => {
	if(phoneForm.phone === phoneNumber.value){
			  uni.showToast({
			  	title: `当前手机号已经是${phoneForm.phone}!`,
				icon: "none"
			  });
			  return;
	}
  phoneFormRef.value.validate().then(async () => {
	 const res = await updatePhone({
	   phone: phoneForm.phone,
	   code: phoneForm.phoneCode
	 }).catch(e => {
	   console.log(e)
	   uni.showToast({
	     title: '设置失败',
	     icon: 'none'
	   })
	 });
	 if(res.code === 200){
	   // 设置密码成功后关闭弹窗
	 		  // 验证成功
	 		  showPhoneInputPopup.value = false;
	 		  // 更新显示的手机号（隐藏中间4位）
	 		  const phone = phoneForm.phone;
	 		  phoneNumber.value = phone;
	   uni.showToast({
	     title: '设置成功',
	     icon: 'success'
	   });
	   uni.reLaunch({
		url:"/pages/login/login"
	   })
	 }else{
	   uni.showToast({
	     title: res.msg,
	     icon: 'none'
	   });
	 }
    })
    .catch(errors => {
      // 表单验证失败
      console.log('表单验证失败：', errors);
    });
};

// 打开设置密码弹窗 - 先验证手机
const openSetPasswordPopup = async () => {
  // showBindPhonePopup.value = true;
  const res = await getUpdateCode(phoneNumber.value).catch(error => { 
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none'
    });
    console.log(error)
  });
  if(res.code === 200){
  // 先打开手机验证弹窗
    showBindPhonePopup.value = true;
  }else{
    console.log(res)
    uni.showToast({
      title: res.msg,
      icon: 'none'
    });
  }

 
};

// 重新发送验证码
const resendVerificationCode = async() => {
   const res = await getUpdateCode(phoneNumber.value).catch(error => { 
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none'
    });
    console.log(error)
  });
  if(res.code === 200){
    uni.showToast({
      title: '验证码已重新发送',
      icon: 'success'
    });
  }else{
    console.log(res)
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none'
    });
  }
};


onShow(() => {
  flushInfo()
})
</script>

<style lang="scss" scoped>
.setting-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.content-container {

  margin-top: 20rpx;
}

.setting-item {
  background-color: #ffffff;
  display: flex;
  align-items: center;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx; // 添加圆角

  &__label {
    font-size: 32rpx;
    color: #303133;
    margin-right: 20rpx; // 与内容保持间距
  }

  &__content {
    display: flex;
    align-items: center;
    flex: 1; // 让内容占据剩余空间
  }
}

// 绑定手机号项特定样式 - 使用更高优先级
.setting-item.phone-item {
  justify-content: space-between !important;
}

.setting-item.phone-item .setting-item__content {
  justify-content: flex-end !important;
}

.phone-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e4e7ed;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-bottom: 10rpx;
}

/* 适配验证码按钮 */
.u-form-item {
  position: relative;
}

.u-form-item__right {
  flex: 0 0 auto;
  margin-left: 10px;
}

.form-item {
  // margin-bottom: 30rpx;
  position: relative;
}

.phone-number {
  font-size: 32rpx;
color: #909399;
  margin-right: 20rpx;
}

.password-status {
  font-size: 30rpx;
  font-weight: bolder;
  color: #909399;
  margin-right: 16rpx;
}

.protection-tag {
 line-height: 10pt;
background-color: rgba(255,203,167,1);
color: rgba(16,16,16,1);
font-size: 20rpx;
text-align: center;
  padding: 6rpx 16rpx;
  // border-radius: 20rpx;
  // margin-right: 20rpx;
}

.modify-link {
  font-size: 28rpx;
  color: #2979ff;
  font-weight: 500;
  text-decoration: none;
  margin-left: auto; // 推到最右侧
}

/* 弹窗样式 */
.popup-container {
  padding: 30rpx 40rpx;
  background-color: #ffffff;
  border-radius: 16rpx 16rpx 0 0;
}

.popup-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #303133;
	text-align: center;
	margin-bottom: 30rpx;
}

.popup-content {
  margin-bottom: 30rpx;
}

.verification-info {
  font-size: 28rpx;
  color: #303133;
  margin-bottom: 20rpx;
}

.phone-highlight {
  color: #2979ff;
  font-weight: 500;
}

.verification-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e4e7ed;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-bottom: 10rpx;
}

/* 表单验证错误提示样式 */
.u-form-item__error-message {
  font-size: 24rpx;
  color: #f56c6c;
  margin-top: 8rpx;
  margin-bottom: 20rpx;
}

.time-info {
  font-size: 24rpx;
  color: #909399;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 30rpx;
}

.resend-link {
  color: #2979ff;
}

.password-item {
  margin-bottom: 20rpx;
}

.password-label {
  font-size: 28rpx;
  color: #303133;
  margin-bottom: 10rpx;
}

.password-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e4e7ed;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-bottom: 10rpx;
}

.confirm-button {
  width: 100%;
  height: 90rpx;
  background-color: #2979ff;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin-top: 20rpx;
}

/* 适配底部弹窗的遮罩层 */
.u-popup__mask {
  background-color: rgba(0, 0, 0, 0.5);
}
</style>